<?php

namespace StudyBuddy\FS;

/**
 * Class for preparing and resolving file path
 * based on id using dec2hex and hex2dec file storage
 * scheme.
 *
 */
class Path {

    /**
     * It is used to verify or create the path of the file (using HEX logic)
     *
     * @param int $intResourceId  resource id
     * the path will be created based on this integer
     *
     * @param string $destinationDir directory in which
     * the path will be created.
     *
     * @return string a hex path (without file extension)
     * OR a full path, including the destinationDir prefix
     * if $bReturnFullPath param is true
     *
     */
    public static final function prepare($intResourceId, $destinationDir = '', $bReturnFullPath = false) {

        if (!is_numeric($intResourceId)) {
            throw new \InvalidArgumentException('$intResourceId must be numeric, ideally an integer. Was: ' . $intResourceId);
        }

        /**
         * Resource id is converted to hex number
         */
        $destinationDir = \trim((string) $destinationDir);
        $strHex = dechex((int) $intResourceId);
        $strHex = strtoupper($strHex);
        $arrTemp = array();
        $intCount = 0;
        $strPath = '';
        $strFullPathToOrig = '';
        do {
            $intCount++;
            $intRes = preg_match("/([0-9A-F]{1,2})([0-9A-F]*)/", $strHex, $arrTemp);
            //$strHex = $arrTemp[2];
            //d('$strHex: '.$strHex);
            d('$arrTemp: ' . print_r($arrTemp, 1));

            $strPath .= '' . $arrTemp[1];
            if ($arrTemp && ('' !== $arrTemp[2])) {
                $strHex = $arrTemp[2];
                $strPath .= '/';
                //   PATH to Location
                $strFullPathToOrig = $destinationDir . $strPath;

                d('$strFullPathToOrig: ' . $strFullPathToOrig);

                if (!\file_exists($strFullPathToOrig) && !\is_dir($strFullPathToOrig)) {
                    if (!\mkdir($strFullPathToOrig, 0777)) {
                        throw new \StudyBuddy\DevException('Cannot create directory ' . $strFullPathToOrig);
                    }
                }
            }
        } while ($intRes && ($intCount < 10) && ('' !== $arrTemp[2]));

        $ret = ($bReturnFullPath) ? $destinationDir . $strPath : $strPath;

        d(' $ret: ' . $ret);

        return $ret;
    }

    /**
     * Converts the hex path to integer
     * for example:
     * 3E/A
     * is converted to 1002
     * @param string $hex
     * a hex-like path
     *
     * @return integer
     *
     */
    public static function hex2dec($hex) {
        $hex = str_replace('/', '', $hex);

        return hexdec($hex);
    }

}
